
<template>
  <div class="header_information page-container">
    <!-- 头部 -->
    <el-row class="header_name">
      <el-col
        :span="24"
        class="header_text"
      >
        <h1>机构管理</h1>
      </el-col>
      <el-col :span="24">
        <div class="header_line"></div>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row class="el_row_btn">
      <el-col
        :span="24"
        class="content"
      >
        <div class="content_top_btn">
          <div>
            <!-- <el-button
              @click="handleOpenDialogVisible"
              size="large"
              :icon="Plus"
            >邀请机构</el-button> -->
          </div>
          <div>
            <el-space>
              <OrganizingSelect v-model="query_data.agentId" />
              <InstitutionSelect
                :disabled="!query_data.agentId"
                :agentId="query_data.agentId"
                v-model="query_data.institutionId"
              />
              <ProvinceSelect
                :isW="true"
                v-model:economize="query_data.economize"
                v-model:market="query_data.market"
              />
              <!-- 状态选择 -->
              <el-select
                size="large"
                clearable
                v-model="query_data.auditStatus"
                placeholder="请选择审核状态"
              >
                <el-option
                  label="审核通过"
                  value="1"
                />
                <el-option
                  label="等待审核"
                  value="0"
                />
                <el-option
                  label="审核拒绝"
                  value="2"
                />
              </el-select>
              <el-button
                size="large"
                :icon="Search"
                circle
                :loading="loading"
                @click="()=>{handleLoad(true)}"
              />
            </el-space>

          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 内容 -->
    <el-row>
      <el-col :span="24">
        <el-table
          empty-text="暂无机构数据..."
          :data="data"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column
            label="机构 ID"
            prop="userId"
            width="100"
          />

          <el-table-column
            label="机构名称"
            prop="name"
          />
          <el-table-column
            label="组委会名称"
            prop="agentName"
          />
          <el-table-column
            label="负责人姓名"
            prop="headName"
            width="100"
          />
          <el-table-column
            label="电话"
            prop="headPhone"
            width="120"
          />
          <el-table-column
            label="地区"
            prop="address"
          />
          <el-table-column
            prop="state"
            label="审核状态"
            width="100"
            align="center"
          >
            <template v-slot="{ row }">
              <el-tag
                type="warning"
                v-if="row.auditStatus == 0"
              >
                等待审核
              </el-tag>
              <el-tag
                type="success"
                v-if="row.auditStatus == 1"
              >
                审核通过
              </el-tag>
              <el-tag
                type="danger"
                v-if="row.auditStatus == 2"
              >
                审核拒绝
              </el-tag>

            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            prop="Address"
            width="100"
          >
            <template v-slot="{ row }">
              <el-dropdown trigger="click">
                <span class="el_dropdown_link">
                  操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                    <el-dropdown-item @click="handleDel(row)">删除</el-dropdown-item>
                    <el-dropdown-item @click="handleTransfer(row)">转移</el-dropdown-item>
                    <el-dropdown-item @click="handleResetPasswords(row)">重置密码</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 弹窗 -- 分享邀请码 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="分享邀请码"
      width="40%"
    >
      <span class="dialog_text">官网邀请访问地址，邀请完毕后，如果进行注册将自动添加成为您的客户。</span>
      <el-divider />
      <el-input
        class="dialog_inp"
        v-model="dialog.channel_url"
      >
        <template #append>
          <el-button
            type="success"
            @click="handleCopy"
          >复制</el-button>
        </template>
      </el-input>
      <span class="dialog_text">组委会可以通过邀请链接邀请机构进行注册。邀请完毕后，将自动添加成为您的客户。</span>
      <el-divider />
      <el-input
        class="dialog_inp"
        v-model="dialog.input2"
      ></el-input>
    </el-dialog>
    <!-- 弹窗———— 编辑 -->
    <el-dialog
      v-model="centerEditDialogVisible"
      title="编辑机构"
      width="30%"
      align-center
    > <el-form
        :model="form"
        :rules="reg_data_rules"
        ref="reg_data_ref"
      >
        <el-form-item
          label="机构名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            placeholder="请输入机构名称"
            v-model.trim="form.name"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="负责人名称"
          :label-width="formLabelWidth"
          prop="headName"
        >
          <el-input
            placeholder="请输入负责人名称"
            v-model.trim="form.headName"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="负责人手机号"
          :label-width="formLabelWidth"
          prop="headPhone"
        >
          <el-input
            placeholder="请输入负责人手机号"
            v-model.trim="form.headPhone"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="机构地址"
          :label-width="formLabelWidth"
          prop="address"
        >
          <el-input
            v-model.trim="form.address"
            placeholder="请输入机构地址"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerEditDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleEnter"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 弹窗———— 转移 -->
    <el-dialog
      v-model="centerTransferDialogVisible"
      title="转移机构"
      width="30%"
      align-center
    >
      <el-form :model="transferFrom">
        <el-form-item
          label="机构名称"
          :label-width="formLabelWidth"
        >
          <span>
            {{   transferFrom.name }}
          </span>
        </el-form-item>
        <el-form-item
          label="转移到"
          :label-width="formLabelWidth"
        >

          <el-select
            v-model="transferFrom.agentId"
            class="m-2"
            placeholder="选择组委会"
          >
            <el-option
              v-for="item in agents"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            />

          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerTransferDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handletransfer"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="total"
        @current-change="handlePage"
      />
    </div>
  </div>
</template>

<script  setup>
import { useClipboard } from '@vueuse/core'
import {
  Plus,
  WarningFilled,
  Search,
} from "@element-plus/icons-vue";
import InstitutionSelect from "@/components/institution-select/index.vue"
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus';
import { onMounted, ref, watch, markRaw } from "vue";
import {
  findOrganizationListPage,
  getManager,
  resetPassword,
  updateInstitutionInfo,
  deleteAgentOrOrganizer,
  getAgents,
  transfer,
  getInformationByUserId,
} from "@/api/manage/organcommitmenu/index.js";

import OrganizingSelect from "@/components/organizing-select/index.vue"
import ProvinceSelect from "@/components/province-select/index.vue"
import GroupsSelect from "@/components/groups-select/index.vue"

import { usePage } from "@/hooks/usePage"
import { handleCopyFunc } from "@/utils/copy"
const {
  total,
  data,
  loading,
  query_data,
  handleLoad,
  handlePage
} = usePage({
  api_fn: findOrganizationListPage,
  q_data: {
    auditStatus: "",
    agentId: "",
    institution: "",
    rootId: "",
    groupId: "",
    studentName: "",
    phone: "",
    economize: "",
    market: ''
  }
})
// 弹窗
const centerDialogVisible = ref(false)
// 打开弹窗
const handleOpenDialogVisible = () => {
  centerDialogVisible.value = true
}


// 弹窗--编辑 数据回显
const formLabelWidth = '110px'
const centerEditDialogVisible = ref(false)
const form = ref({
  userId: "",
  name: "",
  headName: "",
  headPhone: "",
  address: ""
})
const handleEdit = (row) => {
  form.value = {}
  data.value.forEach(item => {

    if (item.userId === row.userId) {
      // 将匹配的数据填充到表单
      form.value = { ...item }

    }
  })
  centerEditDialogVisible.value = true
}


const checkPhone = (rule, value, callback) => {
  const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/
  if (!value) {
    callback(new Error('手机号码不能为空'))
  }
  if (phoneReg.test(value)) {
    callback()
  } else {
    callback(new Error('手机号码格式错误'))
  }
}
const reg_data_ref = ref();
const reg_data_rules = ref({
  name: [
    {
      type: 'string',
      required: true,
      message: '请输入机构名称',
      trigger: 'blur',
    }
  ],
  headName: [
    {
      type: 'string',
      required: true,
      message: '请输入负责人名称',
      trigger: 'blur',
    }
  ],

  headPhone: [
    {
      required: true,
      validator: checkPhone,
      trigger: 'blur'
    }
  ],
  address: [
    {
      type: 'string',
      required: true,
      message: '请输入地址',
      trigger: 'blur',
    }
  ],


});
// 弹窗--编辑 确定
const handleEnter = async () => {
  reg_data_ref.value.validate(async (v) => {
    if (!v) {
      return;
    }
    centerEditDialogVisible.value = false
    let res = await updateInstitutionInfo(form.value)

    if (res.success) {
      ElMessage({
        message: res.message,
        type: 'success',
      })
      handleLoad(true);
    }
  });
}

// 全选
const multipleSelection = ref([])
const userIds = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  userIds.value = multipleSelection.value.map((item) => item.userId).join(',');

}

// 删除
const handleDel = async (row) => {
  ElMessageBox.confirm("是否确定删除当前机构？", "删除机构", { type: "error" }).then(async () => {
    if (row.userId) {
      let res = await deleteAgentOrOrganizer(row.userId)

      if (res.success) {
        ElNotification({
          title: '成功',
          message: `删除${res.message}`,
          type: 'success',
        })
      } else {
        ElMessage.error(res.message)
      }
    } else if (userIds.value) {
      let res = await deleteAgentOrOrganizer(userIds.value)

      if (res.success) {
        ElNotification({
          title: '成功',
          message: `删除${res.message}`,
          type: 'success',
        })
      } else {
        ElMessage.error(res.message)
      }
    }
    handleLoad(true)
  });
}

// 重置密码
const handleResetPasswords = (row) => {
  const messageText = `您确认重置 ${row.name} (ID : ${row.userId
    }) 的密码?\n密码将重置为 <span style="color: red;">123456</span>`; ElMessageBox.confirm(
      messageText, '密码重置',
      {
        dangerouslyUseHTMLString: true, // 允许使用HTML
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(WarningFilled),
      }
    )
      .then(async () => {

        let res = await resetPassword(row.userId)
        if (res.success) {
          ElMessage({
            message: res.message,
            type: 'success',
          })
        }
      })
      .catch(() => {
        // 用户点击了取消按钮或者关闭了对话框
      });
}
// 转移 1.先获取组委会列表
// 保存查出所有组委会的数据
const agents = ref([])
const handleGetAgents = async () => {
  let res = await getAgents()
  if (res.success) {
    agents.value = res.entityList
  }
}
/*
 转移 2.转移一个机构到其他组委会
**/
//  存储转移的数据
const transferFrom = ref({
  name: "",
  userId: "",
  agentId: ''
})
const centerTransferDialogVisible = ref(false)
const handleTransfer = async (row) => {

  // 避免数据回显
  transferFrom.value = {}
  // 开启弹窗
  centerTransferDialogVisible.value = true
  transferFrom.value.userId = row.userId
  transferFrom.value.name = row.name
  transferFrom.value.agentId = parseInt(row.agentId)
}
/*
 转移 3.确定按钮
 ?userId = 1 & agentId=2
**/
const handletransfer = async () => {
  let res = await transfer({ userId: transferFrom.value.userId, agentId: transferFrom.value.agentId })
  if (res.success) {
    ElMessage({
      title: '成功',
      message: `${res.message}`,
      type: 'success',
    })
  } else {
    ElMessage.error(res.message)
  }
  centerTransferDialogVisible.value = false
  handleLoad(true)
}



// 邀请机构-----------------------------------------------------------------------
let channel = "";
const Host = import.meta.env.VITE_APP_HOST;
try {
  const info_data = localStorage.getItem('info_data')
  channel = JSON.parse(info_data).channel
} catch (error) {

}
const dialog = ref({
  channel_url: `${Host}/auth/reg/?channel=${channel}`,
  input2: ""
})

const { copy } = useClipboard()
const handleCopy = () => {
  handleCopyFunc(dialog.value.channel_url);
  ElMessage.success("复制成功")
}


onMounted(() => {
  handleGetAgents()
  handleLoad(true);
});
</script>

<style lang="scss" scoped>
.header_information {
  padding: 20px;
  .header_name {
    margin-left: 10px;
    margin-right: 10px;
    .header_text {
      margin-left: -10px;
      margin-right: -10px;
    }
    h1 {
      font-size: 28px;
    }
    // 线
    .header_line {
      display: block;
      height: 1px;
      width: 100%;
      margin: 24px 0 20px 0;
      background-color: #8473f717;
    }
  }
  //   内容
  :deep(.table_btn_success) {
    padding: 0 5px !important;
    border: none;
  }
  :deep(.el-table) .cell {
    padding: 0 10px;
  }
  .el_row_btn {
    margin-bottom: 20px;
    .content {
      .content_top_btn {
        display: flex;
        justify-content: space-between;
        .top_search_inp {
          width: 300px;
          height: 40px;
          margin-right: 5px;
        }
        .top_search_btn {
          width: 110px;
          margin-right: 5px;
        }
      }
    }
  }
  .el_dropdown_link {
    font-size: 14px;
  }
  :deep(.el-table)__cell {
    padding: 12px 0 !important;
  }
  // dialog
  .dialog_text {
    .dialog_text {
      display: block;
      margin-top: 20px;
    }
  }
  .dialog_inp {
    height: 40px;
  }
  // 分页
  .pagination {
    margin-top: 30px;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 50px;
  }
}
</style>
